package com.koron.css2.newProjectCenter.callback;

import com.koron.css2.baseConfig.bean.MeterBoreBean;
import com.koron.css2.baseConfig.bean.MeterFactoryBean;
import com.koron.css2.baseConfig.mapper.MeterBoreMapper;
import com.koron.css2.baseConfig.mapper.MeterFactoryMapper;
import com.koron.css2.clientCenter.bean.AccountInfoBean;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.bean.UserBean;
import com.koron.css2.clientCenter.bean.UserChangeItemBean;
import com.koron.css2.clientCenter.impl.OpenUserAdd;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.ChangeUserMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.meterService.bean.MsChgPlanBean;
import com.koron.css2.meterService.bean.MsChgPlanDetailBean;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.meterService.mapper.MsChgPlanDetailMapper;
import com.koron.css2.meterService.mapper.MsChgPlanMapper;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.newProjectCenter.bean.PjInfoBean;
import com.koron.css2.newProjectCenter.bean.PjMeter;
import com.koron.css2.newProjectCenter.bean.PjSettlement;
import com.koron.css2.newProjectCenter.mapper.PjMeterMapper;
import com.koron.css2.newProjectCenter.mapper.PjSettlementMapper;
import com.koron.css2.newProjectCenter.service.PjInfoService;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.NumberUtils;
import com.koron.util.Tools;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 验收节点回调
 */
@Service(PjInfoService.CHECK)
public class CheckCallback implements IPjInfoNodeCallback{

    private static Logger logger = LoggerFactory.getLogger(CheckCallback.class);

    // 水表扩缩
    private static final String PJ_TYPE_3 = "3";

    @Override
    public MessageBean callback(SessionFactory factory, PjInfoBean pjInfoBean, UserInfoBean userInfo) {
        MessageBean info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", Void.class);
        pjSettlemetInsert(factory, userInfo, pjInfoBean);
        // 如果是水表扩缩生成快捷换表数据和变更记录
        if(PJ_TYPE_3.equals(pjInfoBean.getPjType())){
            info = addQuickChange(factory, userInfo, pjInfoBean);
        }
        return info;
    }

    private PjSettlement pjSettlemetInsert(SessionFactory factory, UserInfoBean userInfo, PjInfoBean pjInfoBean){
        PjSettlementMapper pjSettlementMapper = factory.getMapper(PjSettlementMapper.class);
        PjSettlement pjSettlement = new PjSettlement();
        pjSettlement.setBillDate(new Date());
        pjSettlement.setBillNo(Tools.getBillNo(factory, "pj_settlement"));
        pjSettlement.setCreateInfo(userInfo);
        pjSettlement.setConsultBillNo(pjInfoBean.getBillNo());
        pjSettlement.setConsultName(pjInfoBean.getPjName());
        pjSettlement.setBudgetMoney(pjInfoBean.getBudgetMoney());
        pjSettlement.setBudgetCost(NumberUtils.toScaledBigDecimal(pjInfoBean.getBudgetCost()));
        pjSettlement.setBudgetLaborMeterBefore(NumberUtils.toScaledBigDecimal(pjInfoBean.getBudgetLaborMeterBefore()));
        pjSettlement.setBudgetMatrMeterBefore(NumberUtils.toScaledBigDecimal(pjInfoBean.getBudgetMatrMeterBefore()));
        pjSettlement.setSettlementLaborMeterBefore(NumberUtils.toScaledBigDecimal(pjInfoBean.getSetmtLaborMeterBefore()));
        pjSettlement.setSettlementMatrMeterBefore(NumberUtils.toScaledBigDecimal(pjInfoBean.getSetmtMatrMeterBefore()));
        pjSettlement.setDesignCost(NumberUtils.toScaledBigDecimal(pjInfoBean.getDesignCost()));
        pjSettlement.setCostShare(NumberUtils.toScaledBigDecimal(pjInfoBean.getCostShare()));
        pjSettlement.setDepositMoney(NumberUtils.toScaledBigDecimal(pjInfoBean.getDepositMoney()));
        pjSettlement.setConstructionCost(NumberUtils.toScaledBigDecimal(pjInfoBean.getConstructionCost()));
        pjSettlement.setDisposableChargeFlag(pjInfoBean.getDisposableChargeFlag());
        pjSettlement.setSettlementLaborMeterAfter(NumberUtils.toScaledBigDecimal(pjInfoBean.getSetmtLaborMeterAfter()));
        pjSettlement.setBudgetMatrMeterAfter(NumberUtils.toScaledBigDecimal(pjInfoBean.getBudgetMatrMeterAfter()));
        pjSettlement.setBudgetLaborMeterAfter(NumberUtils.toScaledBigDecimal(pjInfoBean.getBudgetLaborMeterAfter()));
        pjSettlement.setRedLineInMoney(pjInfoBean.getRedLineInMoney());
        pjSettlement.setRedLineOutMoney(pjInfoBean.getRedLineOutMoney());
        pjSettlement.setUtensilMoney(pjInfoBean.getUtensilMoney());
        pjSettlement.setSettlementDate(new Date());
        pjSettlement.setConsultId(pjInfoBean.getId());
        pjSettlement.setRedLineInMoney(pjInfoBean.getRedLineInMoney());
        pjSettlement.setRedLineOutMoney(pjInfoBean.getRedLineOutMoney());
        pjSettlement.setUtensilMoney(pjInfoBean.getUtensilMoney());
        pjSettlementMapper.insert(pjSettlement);
        return pjSettlement;
    }

    /**
     * 新增快捷快表数据
     *
     * @return
     */
    public MessageBean<?> addQuickChange(SessionFactory factory, UserInfoBean userInfo, PjInfoBean pjInfoBean) {
        MessageBean<?> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", Void.class);
        try {
            MsChgPlanMapper mapper = factory.getMapper(MsChgPlanMapper.class);
            MsChgPlanDetailMapper msChgPlanDetailMapper = factory.getMapper(MsChgPlanDetailMapper.class);
            ChangeUserMapper changeMapper = factory.getMapper(ChangeUserMapper.class);
            UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);
            CtmInfoMapper ctmInfoMapper = factory.getMapper(CtmInfoMapper.class);
            AccountInfoMapper accountInfoMapper = factory.getMapper(AccountInfoMapper.class);
            MsInfoMapper msInfoMapper = factory.getMapper(MsInfoMapper.class);
            MsChgPlanBean msChgPlan = new MsChgPlanBean();
            MsChgPlanDetailBean msChgPlanDetail = new MsChgPlanDetailBean();
            PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);
            List<PjMeter> pjMeters = pjMeterMapper.getListByConsultId(pjInfoBean.getId());
            PjMeter pjMeter = pjMeters.get(0);
            // 新用户信息
            UserBean newUserInfo = userInfoMapper.getUserInfoById(pjMeter.getUserInfoTempId(), 2);
            // 查询原用户信息
            UserBean oldUserInfo = userInfoMapper.getUserInfoByUserNo(newUserInfo.getUserNo(), 1);
            // 封装换表信息
            setMsChgPlan(msChgPlan, factory, userInfo, pjInfoBean);
            mapper.addMsChgPlan(msChgPlan);
            // 封装换表细节信息
            setMsChaPlanDetail(msChgPlanDetail, factory, oldUserInfo, newUserInfo);
            msChgPlanDetail.setCreateName(userInfo.getUserInfo().getName());
            msChgPlanDetail.setId(Tools.getObjectId());
            msChgPlanDetail.setReceiptId(msChgPlan.getId());
            msChgPlanDetailMapper.addMsChgPlanDetail(msChgPlanDetail);
            // 封装变更记录
            List<UserChangeItemBean> itemBeanList=new ArrayList<>();
            setChangeItem(itemBeanList, msChgPlan, msChgPlanDetail, factory);
            changeMapper.userChangeItemAdd(itemBeanList, 1);

            // 先查出临时的客户和账户数据
            CtmInfoBean ctmInfoTemp = ctmInfoMapper.getCtmInfoById(pjMeter.getUserCtmTempId(), CtmInfoBean.CTMTEMP);
            AccountInfoBean accountInfoTemp = accountInfoMapper.getAccountInfoById(pjMeter.getUserAccountTempId(), AccountInfoBean.ACCOUNTTEMP);
            // 先查出临时用户数据
            UserBean userBeanTemp = userInfoMapper.getUserInfoById(pjMeter.getUserInfoTempId(), UserBean.USERTEMP);
            // 更新用户临时表的客户和账户信息
            userBeanTemp.setCtmNo(ctmInfoTemp.getCtmNo());
            userBeanTemp.setAccountNo(accountInfoTemp.getAccountNo());
            userInfoMapper.userInfoUpdate(userBeanTemp, UserBean.USERTEMP);
            OpenUserAdd openUserAdd = new OpenUserAdd();
            openUserAdd.ctmInfoToUserInfo(ctmInfoTemp, userBeanTemp);
            // 更新正式表中的用户
            UserBean userBean = userInfoMapper.getUserInfoByUserNo(userBeanTemp.getUserNo(), UserBean.USER);
            if (userBean != null) {
                userBeanTemp.setId(userBean.getId());
                userBeanTemp.setCtmNo("");
                userBeanTemp.setAccountNo("");
                userInfoMapper.userInfoUpdate(userBeanTemp, UserBean.USER);
            }
            //  更新旧水表状态，用户编号
            msInfoMapper.updateMsInfoStatus(oldUserInfo.getMeterNo(), 2);
            msInfoMapper.updateMsInfoUserNo(oldUserInfo.getMeterNo(), userBeanTemp.getUserNo());

            info.setDescription("当前扩缩记录，已在营收系统生成快捷换表单据，单据号“"+msChgPlan.getBillNo()+"“");
        }catch (Exception e) {
            e.printStackTrace();
            logger.error("当前扩缩记录，在营收系统中生成快捷换表单据失败:"+e);
            info.setDescription("当前扩缩记录，在营收系统中生成快捷换表单据失败");
        }
        return info;
    }

    /**
     * 封装变更信息
     */
    private void setChangeItem(List<UserChangeItemBean> itemBeanList, MsChgPlanBean msChgPlan, MsChgPlanDetailBean msChgPlanDetail,SessionFactory factory) {
        MeterFactoryMapper meterFactoryMapper = factory.getMapper(MeterFactoryMapper.class);
        MeterBoreMapper meterBoreMapper = factory.getMapper(MeterBoreMapper.class);
        MsInfoMapper msInfoMapper=factory.getMapper(MsInfoMapper.class);

        // 最后抄码
        UserChangeItemBean bean=new UserChangeItemBean();
        bean=new UserChangeItemBean();
        setCommon(msChgPlan, msChgPlanDetail, bean);
        bean.setChangeItem("最后抄码");
        bean.setNewItemValue(String.valueOf(msChgPlanDetail.getNewMeterNum()));
        bean.setOldItemValue(String.valueOf(msChgPlanDetail.getUpperNum()));
        bean.setId(Tools.getObjectId());
        itemBeanList.add(bean);
        // 水表表身码
        bean=new UserChangeItemBean();
        setCommon(msChgPlan, msChgPlanDetail, bean);
        bean.setChangeItem("水表表身码");
        bean.setNewItemValue(msChgPlanDetail.getNewFactoryNo());
        bean.setOldItemValue(msChgPlanDetail.getOldFactoryNo());
        bean.setId(Tools.getObjectId());
        itemBeanList.add(bean);
        // 水表口径
        bean=new UserChangeItemBean();
        setCommon(msChgPlan, msChgPlanDetail, bean);
        bean.setChangeItem("水表口径");
        MeterBoreBean newMeterBore =  meterBoreMapper.selectMeterBoreById(msChgPlanDetail.getNewMeterBore());
        bean.setNewItemValue(newMeterBore==null?"":newMeterBore.getBoreName());
        MeterBoreBean oldMeterBore =  meterBoreMapper.selectMeterBoreById(msChgPlanDetail.getOldMeterBore());
        bean.setOldItemValue(oldMeterBore==null?"":oldMeterBore.getBoreName());
        bean.setId(Tools.getObjectId());
        itemBeanList.add(bean);
        // 水表编号
        bean = new UserChangeItemBean();
        setCommon(msChgPlan, msChgPlanDetail, bean);
        bean.setChangeItem("水表编号");
        bean.setNewItemValue(msChgPlanDetail.getNewMeterNo());
        bean.setOldItemValue(msChgPlanDetail.getOldMeterNo());
        bean.setId(Tools.getObjectId());
        itemBeanList.add(bean);
        // 水表型号
        bean=new UserChangeItemBean();
        setCommon(msChgPlan, msChgPlanDetail, bean);
        bean.setChangeItem("水表型号");
        bean.setNewItemValue(msChgPlanDetail.getNewMeterModel());
        bean.setOldItemValue(msChgPlanDetail.getOldMeterModel());
        bean.setId(Tools.getObjectId());
        itemBeanList.add(bean);
        // 水表厂家
        bean=new UserChangeItemBean();
        setCommon(msChgPlan, msChgPlanDetail, bean);
        bean.setChangeItem("水表厂家");
        MsInfoDto newMsInfo = msInfoMapper.getMsInfoByNo(msChgPlanDetail.getNewMeterNo());
        MeterFactoryBean newMeterFactory = meterFactoryMapper.selectMeterFactoryById(newMsInfo.getMeterFactory());
        bean.setNewItemValue(newMeterFactory==null?"":newMeterFactory.getFactoryName());
        MsInfoDto oldMsInfo = msInfoMapper.getMsInfoByNo(msChgPlanDetail.getOldMeterNo());
        MeterFactoryBean oldMeterFactory = meterFactoryMapper.selectMeterFactoryById(oldMsInfo.getMeterFactory());
        bean.setOldItemValue(oldMeterFactory==null?"":oldMeterFactory.getFactoryName());
        bean.setId(Tools.getObjectId());
        itemBeanList.add(bean);
    }


    /**
     *  相同字段
     */
    private static void setCommon(MsChgPlanBean msChgPlan, MsChgPlanDetailBean msChgPlanDetail, UserChangeItemBean bean) {
        bean.setCreateTime(Tools.getCurrentTime());
        bean.setCreateName(msChgPlan.getCreateName());
        bean.setBillNo(msChgPlan.getBillNo());
        bean.setReceiptId(msChgPlan.getId());
        bean.setReceiptType("换表/快捷换表");
        bean.setUserNo(msChgPlanDetail.getUserNo());
    }

    /**
     * 换表细节信息
     */
    private void setMsChaPlanDetail(MsChgPlanDetailBean msChgPlanDetail,SessionFactory factory, UserBean oldUserInfo, UserBean newUserInfo) throws Exception {
        MsInfoMapper msInfoMapper=factory.getMapper(MsInfoMapper.class);
        msChgPlanDetail.setOldMeterNum(newUserInfo.getOldLastReadingNum());
        msChgPlanDetail.setNewMeterNum(newUserInfo.getLastReadingNum());
        msChgPlanDetail.setConcentratorNo(newUserInfo.getConcentratorNo());
        msChgPlanDetail.setOldHandleWay(2);
        msChgPlanDetail.setReplaceDate(Tools.getDate(newUserInfo.getSetupMeterDate()));
        msChgPlanDetail.setOldMeterNo(oldUserInfo.getMeterNo());
        msChgPlanDetail.setNewMeterNo(newUserInfo.getMeterNo());
        msChgPlanDetail.setMargin(newUserInfo.getOldLastReadingNum()-oldUserInfo.getLastReadingNum());
        msChgPlanDetail.setUpperNum(oldUserInfo.getLastReadingNum());
        msChgPlanDetail.setReplaceStaff(newUserInfo.getMeterBuilder());
        msChgPlanDetail.setReplaceStaffName(newUserInfo.getMeterBuilderName());
        // 获取水表口径
        MsInfoDto oldMsInfoByNo = msInfoMapper.getMsInfoByNo(oldUserInfo.getMeterNo());
        if(oldMsInfoByNo == null){
            throw new Exception();
        }
        msChgPlanDetail.setOldMeterBore(oldMsInfoByNo.getMeterBore());
        MsInfoDto newMsInfoByNo = msInfoMapper.getMsInfoByNo(newUserInfo.getMeterNo());
        if(newMsInfoByNo == null){
            throw new Exception();
        }
        msChgPlanDetail.setNewMeterBore(newMsInfoByNo.getMeterBore());
        msChgPlanDetail.setOldFactoryNo(oldMsInfoByNo.getFactoryNo());
        msChgPlanDetail.setNewFactoryNo(newMsInfoByNo.getFactoryNo());
        msChgPlanDetail.setOldMeterModel(oldMsInfoByNo.getMeterModel());
        msChgPlanDetail.setNewMeterModel(newMsInfoByNo.getMeterModel());
        msChgPlanDetail.setUserNo(newUserInfo.getUserNo());
    }

    /**
     * 换表信息
     */
    private void setMsChgPlan(MsChgPlanBean msChgPlan, SessionFactory factory, UserInfoBean userInfo, PjInfoBean pjInfoBean) {
        msChgPlan.setMeterAmount(1);
        msChgPlan.setBillDate(new Date());
        msChgPlan.setBackfillAmount(0);
        msChgPlan.setReceiptType(1);
        msChgPlan.setBillNo(Tools.getBillNo(factory, "MS_CHG_PLAN")); //生成单据
        msChgPlan.setCreateInfo(userInfo);
        msChgPlan.setReplaceReason("根据报装登记水表扩缩单据自动生成，报装登记单据号“"+pjInfoBean.getBillNo()+"”");
        msChgPlan.setProcessState("END");
        msChgPlan.setCreateName("系统制单");
        msChgPlan.setCreateTime(Tools.getCurrentTime());
        msChgPlan.setReplaceType(1);
        msChgPlan.setBatchType(2);
        msChgPlan.setUpdateTime(Tools.getCurrentTime());
        msChgPlan.setUpdateName("系统制单");
    }
}
